package frog.lazy.framework.http.controller;

import cn.hutool.log.StaticLog;
import frog.lazy.framework.core.dto.ResultDto;
import frog.lazy.framework.core.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@Slf4j
public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController {

    private final String path_default = "/error";
    private final String NOT_FUND = "404";

    @Override
    public String getErrorPath() {
        return path_default;
    }

    @RequestMapping(value = path_default,  produces = {MediaType.APPLICATION_JSON_VALUE})
    public Object error(HttpServletRequest request, HttpServletResponse response) {
        Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
        String status_code = String.valueOf(request.getAttribute("javax.servlet.error.status_code"));
        if(NOT_FUND.equals(status_code)) {
            return ResultDto.error("请求地址不存在");
        }
        response.setStatus(HttpStatus.OK.value());
        return handlerException(exception);
    }

    private Object handlerException(Exception throwable) {
        if(throwable.getCause() instanceof BizException){
            BizException be = (BizException) throwable;
            if(be.getCode() == BizException.NO_LOGIN) {
                return ResultDto.noLogin(be.getMsg());
            }else if(be.getCode() == BizException.FAIL) {
                return ResultDto.fail(be.getMsg());
            } else {
                return ResultDto.error(be.getMsg());
            }
        }else {
            if(null != throwable) {
                StaticLog.error("【未处理异常】->\n{}", throwable.getMessage());
                throwable.printStackTrace();
            }
            return ResultDto.error("网络异常");
        }
    }
}
